<!-- 数据源管理 -->
<template>
  <div>
    <div v-if="!currentMetaData.id" class="children_content">
      <div class="add_btns_box">
        <div class="box_left">
          <div class="title">元数据列表</div>
        </div>
        <div class="box_right">
          <Space>
            <Button type="primary" @click="impExcelDialogDisplay = true" icon="ios-log-in">导入元数据文件</Button>
            <Button type="primary" @click="handleExport()">导出选中结果</Button>
            <Button type="primary" @click="impSelectShow = true">导入元数据</Button>
            <Button type="error" @click="handleBatdelete()">批量删除</Button>
          </Space>
        </div>
      </div>

      <Tabs v-model="tabActive" @on-click="tabChange">
        <TabPane v-for="item in TAB_OPTIONS" :key="item.value" :label="item.label"
          :name="item.value" />
      </Tabs>

      <div class="content_table">
        <TemplateTable ref="templateTableRef" :data="tableData" :columns="tableColumns" :loading="loading"
          :height="tableHeight" checkbox :page="pageIndex" :page-size="pageSize" :total="total" border="none"
          size="small" stripe @page-change="handlePageChange"
          @link-click="handleLinkClick">
          <template #fromdb="{ row }">
            <Icon v-if="row.fromdb" type="md-checkmark" color="#0a0" />
          </template>
        </TemplateTable>
      </div>
    </div>

    <ChildContent v-if="currentMetaData.id" :currentMetaData="currentMetaData" @back="currentMetaData = {}" />

    <ImpSelect ref="impSelectRef" v-if="impSelectShow" @cancel="handleDialogCancel"
      @submit="handleDialogSubmit" />

    <ImpExcelDialog v-if="impExcelDialogDisplay" />

    <EditDialog ref="editDialogRef" v-if="editDialogDisplay" @submit="editSuccess" @cancel="editDialogDisplay = false" />
  </div>
</template>

<script setup>
import { ref, onMounted, getCurrentInstance, inject, watch, nextTick, computed } from 'vue'
import { Message } from 'view-ui-plus'
import moment from 'moment'

import { metadata } from '@/api/modules/modelSetting'

import ImpSelect from './components/ImpSelect.vue'
import ImpExcelDialog from './components/ImpExcelDialog.vue'
import EditDialog from './components/EditDialog.vue'
import ChildContent from './ChildContent/index.vue'

// 屏幕高度
const screenHeight = inject('screenHeight')
// 搜索组件高度
const searchHeight = ref(null)
// 表格高度
const tableHeight = ref(0)
// 监听 screenHeight 的变化
watch(
  screenHeight,
  newHeight => {
    tableHeight.value = newHeight - 275
  },
  { immediate: true }
)

const TAB_OPTIONS = [
  { label: '普通数据表', value: '1' },
  { label: 'SQL数据表', value: '2' },
  { label: 'ES数据表', value: '3' },
  { label: '数据模型', value: '5' },
  { label: '外部数据源', value: '6' }
]
const currentMetaData = ref({})
const tabActive = ref(TAB_OPTIONS[0].value)
const impExcelDialogDisplay = ref(false)
const editDialogDisplay = ref(false)
// 是否显示对话框
const impSelectShow = ref(false)
const impSelectRef = ref(null)
const templateTableRef = ref(null)
const editDialogRef = ref(null)


// 当前对象
const { proxy } = getCurrentInstance()

const pageIndex = ref(1)
const pageSize = 20
const total = ref(0)

// 列表数据
const tableData = ref([])

// 加载状态
const loading = ref(false)

// 表格列配置
const tableColumns = computed(() => [
  { title: '中文名', field: 'name', type: 'link', minWidth: 200 },
  { title: '表名', field: 'tablename', minWidth: 200 },
  { title: '代码', field: 'code', minWidth: 140 },
  { title: '类型', field: 'tabletype', minWidth: 120, formatter: ({ row }) => {
    const rowData = TAB_OPTIONS.find(item => item.value === row.tabletype)
    return rowData?.label
  } },
  { title: 'ES数据', field: 'fromdb', slot: 'fromdb', minWidth: 140},
  {
    title: '创建时间',
    field: 'createtime',
    minWidth: 140,
    formatter: ({ row }) => {
      return row.createtime ? moment(row.createtime).format('YYYY-MM-DD HH:mm:ss') : ''
    }
  },
  { title: '备注', field: 'eventname', minWidth: 140 },
  {
    title: '操作',
    type: 'action',
    width: 140,
    fixed: 'right',
    actions: [
      {
        text: '编辑',
        type: 'edit',
        onClick: row => handleEdit(row)
      },
      {
        text: '删除',
        type: 'del',
        onClick: row => handleDelete(row)
      }
    ]
  }
])

const tabChange = () => {
  getPageData(true)
}

const handleLinkClick = (data) => {
  currentMetaData.value = data.row
}

// 批量删除
const batchDel = () => {
  proxy.$Modal.confirm({
    mask: false,
    title: '警告',
    content: '<p>是否批量删除选中数据?</p>',
    okText: '确认',
    cancelText: '取消',
    onOk: () => {
      Message.success('批量删除成功')
      getPageData(true)
    }
  })
}

// 编辑数据源
const handleEdit = row => {
  editDialogDisplay.value = true
  nextTick(() => {
    editDialogRef.value.initDialog(row.id)
  })
}

const handleTest = data => {
  metadata
    .test({
      data: {
        id: data.id
      }
    })
    .then(() => {
      Message.success('测试成功')
    })
    .catch(() => {
      Message.error('测试失败')
    })
}

const handleDelete = row => {
  proxy.$Modal.confirm({
    mask: false,
    title: '警告',
    content: '<p>是否删除该数据?</p>',
    okText: '确认',
    cancelText: '取消',
    onOk: async () => {
      await metadata.delete({
        data: {
          id: row.id
        }
      })
      Message.success('删除成功')
      getPageData(true)
    }
  })
}

// 处理对话框取消
const handleDialogCancel = () => {
  impSelectShow.value = false
}

// 处理对话框提交
const handleDialogSubmit = () => {
  impSelectShow.value = false
  getPageData(true)
}

const getPageData = reset => {
  if (reset) {
    pageIndex.value = 1
  }

  loading.value = true

  metadata
    .page({
      query: {
        p: pageIndex.value,
        ps: pageSize
      },
      data: {
        tabletype: tabActive.value
      }
    })
    .then(({ data }) => {
      tableData.value = data?.content || []
      total.value = data?.totalElements || 0
    })
    .finally(() => {
      loading.value = false
    })
}

// 处理页码变化
const handlePageChange = page => {
  pageIndex.value = page
  getPageData()
}

const handleExport = () => {
  const list = templateTableRef.value.getCheckboxRecords()
  console.log(list)
}

const handleBatdelete = () => {
  const list = templateTableRef.value.getCheckboxRecords()
  if(!list.length) return Message.error('请选择需要删除的数据')

  proxy.$Modal.confirm({
    mask: false,
    title: '警告',
    content: '<p>是否批量删除数据?</p>',
    okText: '确认',
    cancelText: '取消',
    onOk: async () => {
      await metadata.batdelete({
        query: {
          ids: list.map(item=>item.id)
        }
      })
      Message.success('删除成功')
      getPageData(true)
    }
  })
}

const editSuccess = () => {
  editDialogDisplay.value = false
  getPageData()
}

onMounted(() => {
  getPageData()
})
</script>

<style lang="scss" scoped>
:deep(.ivu-tabs) .ivu-tabs-bar {
  margin-bottom: 0;
}
</style>